<?php defined('SYSPATH') or die('No direct script access.');

class Model_Brand extends ORM
{  
    protected $_reload_on_wakeup = false;
    
    protected static function _compare($a, $b)
    {
        return $a['count'] < $b['count'];
    }
    
    public function get_brands(Model_Category $category, $limit = 7)
    {
        // TODO cache
        if ($brands = Cache::instance()->get('category_brands_'.$category->id)) {
            return $brands;
        }
        
        $stat = array();
        $tmp_stat = DB::select('brand_id', array(DB::expr('COUNT( * )'), 'count'))
                    ->from('models')
                    ->where('category_id', '=', $category->id)
                    ->group_by('brand_id')
                    ->order_by('count', 'DESC')
                    ->execute()
                    ->as_array();
        
        $ids = array();
        foreach ($tmp_stat as $item) {
            $ids[] = $item['brand_id'];
            $stat[$item['brand_id']] = $item['count'];    
        }
        $brands = array();
        $tmp_brands = ORM::factory('brand')
                        ->where('id', 'IN', $ids)
                        ->find_all()
                        ->as_array();
        foreach ($tmp_brands as $brand) {
            $brand = $brand->as_array(); 
            $brands[$brand['id']] = $brand;
            $brands[$brand['id']]['count'] = $stat[$brand['id']];            
        } 
        usort($brands, array(__CLASS__, '_compare'));  
        
        $result = array(
            'main'  => array(),
            'other' => array(),
        );
        $i = 0;
        foreach ($brands as $brand) {
            if ($i < $limit) {
                $result['main'][] = $brand;         
            } else {
                $result['other'][] = $brand;    
            } 
            $i++;   
        }  
        
        Cache::instance()->set('category_brands_'.$category->id, $result);
        return $result;                                                
    }
    
}